package com.sx.service.design;

import com.sx.basic.ResponseEntity;
import com.sx.basic.pageable.Condition;
import com.sx.basic.service.BasicService;
import com.sx.basic.service.impl.BasicServiceImpl;
import com.sx.dao.design.PageRepository;
import com.sx.design.IDesignModuleService;
import com.sx.design.IPageModuleService;
import com.sx.design.IPageService;
import com.sx.entity.design.PageEntity;
import com.sx.entity.design.PageModuleEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author AdinZ
 * @date 2020/11/18 10:12
 */
@Service
public class PageService extends BasicServiceImpl<PageRepository, PageEntity,Long>
        implements BasicService<PageEntity,Long>, IPageService {

    @Resource private IPageModuleService pageModuleService;
    @Resource private IDesignModuleService moduleService;

    @Override
    public ResponseEntity<PageEntity> pageDetail(long id) {
        PageEntity entity = get(id);
        if(entity==null)return toError();
        List<PageModuleEntity> list = this.pageModuleService.findList(new Condition().eq("pageId", id));
        if(list!=null&&list.size()>0){
            list.forEach(e-> {
                e.setModule(this.moduleService.getDetail(e.getModuleId()));
            });
        }
        entity.setList(list);
        return toSuccess(entity);
    }

    @Override
    public ResponseEntity putDetail(String action, PageEntity entity) {
        if(entity.getId()==null){
            List<PageEntity> list = this.findList(new Condition().eq("pagekey", entity.getPagekey()));
            if(list!=null&&list.size()>0)return this.toError("页面唯一值已存在");
            this.save(entity);
        }else {
            if(StringUtils.isEmpty(action)) {
                this.update(entity);
                return toSuccess();
            }
            if(!StringUtils.equals("detail",action)){
                return toError();
            }
            pageModuleService.delete(new Condition().eq("pageId", entity.getId()));
            if(entity.getList()!=null&&entity.getList().size()>0) {
                entity.getList().forEach(e -> e.setPageId(entity.getId()));
                pageModuleService.save(entity.getList());
            }
            this.update(entity);
            return toSuccess();
        }
        return toSuccess();
    }
}
